import { useCallback } from "react";
import { useRecoilState } from "recoil";

import { userState } from "./../stores/user";

const apiUrl = import.meta.env.VITE_BASE_URL;

interface Config extends RequestInit {
  data?: any;
  token?: string;
  
}

/**公共的 HTTP 请求封装 */
export const downloadFile = <T>(
  endpoint: string,
  {  token }: Config = {}
) => {

  return window
    .fetch(`${apiUrl}${endpoint}`, {
      method:'GET',
      headers:{
        token:token || '',
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
    })
    .then((response) => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.blob()
    })
    .then((data)=>{
      
      return data;

    })
    .catch((e:any) => {
      console.log(e,'err')
      
    });
};

export const useDowLoad = <T>() => {
  const [user] = useRecoilState(userState);
  return useCallback(
    (...[endpoint, config]: Parameters<typeof downloadFile>) =>
      downloadFile<T>(endpoint, { ...config, token: user?.token || "" }),
    [user?.token]
  );
};
